package libra;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class SwService {
	@Autowired
	JdbcTemplate jt;
	
	public void insert() {
		jt.update("insert into `test` values(1,'a')");
	}
	
	public void save( ReqRecord record ) throws Throwable {
		String callJson = new ObjectMapper().writeValueAsString( record.getCall() );
		
		KeyHolder keyHolder = new GeneratedKeyHolder();
		int row = jt.update(new PreparedStatementCreator() {
			@Override
			public PreparedStatement createPreparedStatement(Connection con)
					throws SQLException {
				PreparedStatement ps = con.prepareStatement("INSERT INTO `test` (`localService`, `recordTime`, `call`) VALUES (?, ?, ?);", Statement.RETURN_GENERATED_KEYS);
				ps.setObject(1, record.getLocalService());
				ps.setObject(2, record.getRecordTime());
				ps.setObject(3, callJson );
				return ps;
			}
		}, keyHolder);
		if (row > 0) {
			Number num = keyHolder.getKey();
			if (num != null)
				record.setId( num.intValue() );
		}
//		details.checkEx();
	}
}
